//
//  LLClientManager.m
//  LLWeChat
//
//  Created by GYJZH on 7/20/16.
//  Copyright © 2016 GYJZH. All rights reserved.
//

#import "LLClientManager.h"
#import "LLConfig.h"
#import "LLChatManager.h"
#import "LLMacro.h"
#import "LLUserProfile.h"
#import <MHPopupAlert.h>

@interface LLClientManager ()

@end


@implementation LLClientManager

CREATE_SHARED_MANAGER(LLClientManager)

- (instancetype)init {
    self = [super init];
    if (self) {
        [[EMClient sharedClient] addDelegate:self delegateQueue:nil];
        
//        [[NSNotificationCenter defaultCenter] addObserver:self
//                                                 selector:@selector(loginStateChange:)
//                                                     name:kNOTIFICATION_LOGINCHANGE
//                                                   object:nil];
    }
    
    return self;
}
-(void)initializeSDKWithOptionsIsAutoLogin:(BOOL)isAutoLogin appkey:(NSString *)Appkey apnsCertName:(NSString *)apnsCertName{
    //初始化EMClient
    EMOptions *options = [EMOptions optionsWithAppkey:Appkey];
    options.apnsCertName = apnsCertName;
    options.isAutoAcceptGroupInvitation = NO;
    options.isAutoAcceptFriendInvitation = NO;
    options.isAutoLogin = isAutoLogin;
    options.enableConsoleLog = YES;
    options.isSandboxMode = NO; //YES为SDK内部测试使用
    [[EMClient sharedClient] initializeSDKWithOptions:options];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
/**
 *  该方法后台登出，同时负责HUD显示
 */
- (void)logout:(void(^)(EMError *error))complete{
    [[EMClient sharedClient].options setIsAutoLogin:NO];
    [[EMClient sharedClient] logout:NO completion:^(EMError *aError) {
        [[EMClient sharedClient].options setIsAutoLogin:NO];
        !complete ?: complete(aError);
    }];
}
//- (void)loginStateChange:(NSNotification *)notification {
//    NSLog(@"登陆通知 %@",notification.userInfo);
//}
- (void)loginWithUsername:(NSString *)username password:(NSString *)password complete:(void(^)(EMError *error))complete{
    MH_WEAK_SELF;
    [[EMClient sharedClient] loginWithUsername:username password:password completion:^(NSString *aUsername, EMError *error) {
        if (!error) {
            [[LLUserProfile myUserProfile] initUserProfileWithUserName:username nickName:username avatarURL:nil];
            //SDK要求
            [[EMClient sharedClient] dataMigrationTo3];
            //获取消息推送通知
            [weakSelf loadPushOptionsFromServer];
            //获取联系人
            [[LLContactManager sharedManager] asynGetContactsFromServer:nil];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            !complete ?: complete(error);
        });
        [weakSelf saveLastLoginUsername:username];
    }];
    
}
#pragma mark - 推送设置 -
- (void)loadPushOptionsFromServer {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMError *error = nil;
        EMPushOptions *pushOptions = [[EMClient sharedClient] getPushOptionsFromServerWithError:&error];
        if (!error) {
            LLPushOptions *llPushOptions = [LLUserProfile myUserProfile].pushOptions;
            llPushOptions.displayStyle = (LLPushDisplayStyle)pushOptions.displayStyle;
            llPushOptions.noDisturbSetting = (LLPushNoDisturbSetting)pushOptions.noDisturbStatus;
            llPushOptions.noDisturbingStartH = pushOptions.noDisturbingStartH;
            llPushOptions.noDisturbingEndH = pushOptions.noDisturbingEndH;
            
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            NSString *userName = [EMClient sharedClient].currentUsername;
            NSString *key = [NSString stringWithFormat:@"%@_%@",userName, PUSH_OPTIONS_VIBRATE_KEY];
            
            id setting = [userDefaults objectForKey:key];
            if (setting) {
                llPushOptions.isVibrateEnabled = [setting boolValue];
            }else {
                llPushOptions.isVibrateEnabled = YES;
            }
            
            key = [NSString stringWithFormat:@"%@_%@",userName, PUSH_OPTIONS_SOUND_KEY];
            setting = [userDefaults objectForKey:key];
            if (setting) {
                llPushOptions.isAlertSoundEnabled = [setting boolValue];
            }else {
                llPushOptions.isAlertSoundEnabled = YES;
            }
            
        }else {
            NSLog(@"PushOptions Error");
        }
    });
}
- (void)saveLastLoginUsername:(NSString *)username {
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setValue:username forKey:LAST_LOGIN_USERNAME_KEY];
    [ud synchronize];
}


/*!
 *  \~chinese
 *  自动登录完成时的回调
 *
 *  @param aError 错误信息
 *
 *  \~english
 *  Invoked when auto login is completed
 *
 *  @param aError Error
 */
- (void)autoLoginDidCompleteWithError:(EMError *)aError{
    [[NSNotificationCenter defaultCenter] postNotificationName:LLClientAutoLoginCompleteNotification object:aError];
}
/*!
 *  \~chinese
 *  当前登录账号在其它设备登录时会接收到此回调
 *
 *  \~english
 *  Invoked when current IM account logged into another device
 */
- (void)userAccountDidLoginFromOtherDevice{
    [self logout:nil];
    [MHPopupAlert showMessageAlertWithTitle:@"您的账号在其他设备登录" message:nil actionTitle:@"确定" actionHandler:^{
        [[NSNotificationCenter defaultCenter] postNotificationName:kNOTIFICATION_LOGINCHANGE object:nil userInfo:@{@"loginStatus":@NO,@"jump":@YES}];
    }];
}
/*!
 *  \~chinese
 *  当前登录账号被强制退出时会收到该回调，有以下原因：
 *    1.密码被修改；
 *    2.登录设备数过多；
 *
 *  \~english
 *  Delegate method will be invoked when current IM account is forced to logout with the following reasons:
 *    1. The password is modified
 *    2. Logged in too many devices
 */
- (void)userAccountDidForcedToLogout:(EMError *)aError{
    [[NSNotificationCenter defaultCenter] postNotificationName:kNOTIFICATION_LOGINCHANGE object:nil userInfo:@{@"loginStatus":@NO,@"jump":@YES}];
}
@end
